package com.czy.daishusys.ui.login;

import android.content.DialogInterface;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.czy.daishusys.R;
import com.czy.daishusys.db.UserHelper;
import com.czy.daishusys.global.Constants;
import com.czy.daishusys.ui.BaseActivity;
import com.czy.daishusys.ui.personal.ModifyPasswordActivity;
import com.czy.daishusys.utils.ActivityHelper;
import com.czy.daishusys.utils.GetDeviceId;
import com.czy.daishusys.utils.JsonUtil;
import com.czy.daishusys.utils.MyLog;
import com.czy.daishusys.utils.PhoneUtils;
import com.czy.daishusys.utils.PicDialog;
import com.czy.daishusys.widget.MyEditText;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import butterknife.BindView;
import butterknife.OnClick;

public class ForgetPasswordActivity extends BaseActivity {

    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_subtitle)
    TextView toolbarSubtitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.et_mobile)
    MyEditText etMobile;
    @BindView(R.id.et_sms_code)
    MyEditText etSmsCode;
    @BindView(R.id.et_passwd)
    MyEditText etPasswd;
    @BindView(R.id.et_ensure_passwd)
    MyEditText etEnsurePasswd;
    @BindView(R.id.btn_ensure)
    Button btnEnsure;
    @BindView(R.id.btn_get_sms_code)
    TextView btnGetSmsCode;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_forget_password;
    }

    @Override
    protected void initInjector() {
        getToolbarTitle().setText(R.string.forget_passwd_title);
        showBack();
    }

    @Override
    protected void initViews() {

    }

    @Override
    protected void updateViews() {

    }

    @OnClick({R.id.btn_get_sms_code,R.id.btn_ensure})
    protected void OnViewClicked(View view){
        switch (view.getId()){
            case R.id.btn_get_sms_code:
                checkAndRequestSmsCode();
                break;
            case R.id.btn_ensure:
                checkAndResetPassword();
                break;
        }
    }

    private void checkAndResetPassword(){
        String phone = etMobile.getText().toString().trim();
        String smsCode = etSmsCode.getText().toString().trim();
        String password = etPasswd.getText().toString();
        String rePassword = etEnsurePasswd.getText().toString();
        boolean canRest = true;
        View focusView = null;

        //检查确认密码
        if(!password.equals(rePassword)){
            etEnsurePasswd.setError(getString(R.string.modify_password_diff));
            focusView = etEnsurePasswd;
            canRest = false;
        }

        //检查第一次密码长度
        if (password.length() < 6) {
            etPasswd.setError(getString(R.string.invalid_password_length_min));
            focusView = etPasswd;
            canRest = false;
        }

        if (password.length() > 20) {
            etPasswd.setError(getString(R.string.invalid_password_length_max));
            focusView = etPasswd;
            canRest = false;
        }

        //检查短信验证码
        if (TextUtils.isEmpty(smsCode)) {
            focusView = etSmsCode;
            etSmsCode.setError(getString(R.string.invalid_sms_code));
            canRest = false;
        }

        // 检查手机号
        if (TextUtils.isEmpty(phone)) {
            etMobile.setError(getString(R.string.invalid_mobile_empty));
            focusView = etMobile;
            canRest = false;
        } else if (!PhoneUtils.isMobileNO(phone)) {
            etMobile.setError(getString(R.string.invalid_mobile));
            focusView = etMobile;
            canRest = false;
        }

        if (canRest) {
           resetPassword(phone,smsCode,password);
        } else {
            focusView.requestFocus();
        }


    }

    private void resetPassword(String phone, String smsCode, String password) {

        HttpParams params =  new HttpParams();
        params.put("phone", phone);
        params.put("newPassword", password);
        params.put("smsCode", smsCode);
        params.put("pid", UserHelper.getInstance().getDevicePid());
        mMProgressDialog.show();
        EasyHttp.post(Constants.RESET_PASSWORD_BY_SMS)
                .params(params)
                .timeStamp(true)//添加时间戳
                .execute(new SimpleCallBack<String>() {

                    @Override
                    public void onError(ApiException e) {
                        mMProgressDialog.dismiss();
                        PhoneUtils.ShowToastMessage(ForgetPasswordActivity.this, e.getMessage());
                    }

                    @Override
                    public void onSuccess(String s) {

                        mMProgressDialog.dismiss();
                        String data = PhoneUtils.checkResponseFlag(ForgetPasswordActivity.this,s);
                        if(data != null){
                            PicDialog.Builder builder = new PicDialog.Builder(ForgetPasswordActivity.this)
                                    .setTitleIcon(R.mipmap.ic_dialog_title_passwd)
                                    .setTitle("密码重置成功");
                            final PicDialog dialog = builder.create();
                            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                                @Override
                                public void onDismiss(DialogInterface dialogInterface) {
                                    ActivityHelper.getInstance().finishAllActivity();
                                    LoginActivity.navToLogin(ForgetPasswordActivity.this);
                                }
                            });
                            dialog.show();
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    dialog.dismiss();
                                }
                            },1000);
                        }
                    }
                });
    }

    /**
     * 校验手机号，并获取短信验证码
     * */
    private void checkAndRequestSmsCode(){
        String phone = etMobile.getText().toString().trim();
        if (!PhoneUtils.isNetworkConnected(this)) {
            return;
        }

        if (TextUtils.isEmpty(phone)) {
            PhoneUtils.ShowToastMessage(this, getString(R.string.invalid_mobile_empty));
            etMobile.requestFocus();
            return;
        }

        if (!PhoneUtils.isMobileNO(phone)) {//本地验证手机格式
            PhoneUtils.ShowToastMessage(this, getString(R.string.invalid_mobile));
            etMobile.requestFocus();
            return;
        }

        HttpParams params =  new HttpParams();
//        params.put("session", UserHelper.getInstance().getSessionInfoModel(this).getSession());
        params.put("phone", phone);
        params.put("pid", new GetDeviceId(this).getCombinedId());
        MyLog.d(TAG,"param = "+params.toString());
        mMProgressDialog.show();
        EasyHttp.post(Constants.REQ_SMS_CODE_RESET)
                .baseUrl(Constants.APP_API_BASE)
                .params(params)
                .timeStamp(true)//添加时间戳
                .execute(new SimpleCallBack<String>() {

                    @Override
                    public void onError(ApiException e) {
                        mMProgressDialog.dismiss();
                        PhoneUtils.ShowToastMessage(ForgetPasswordActivity.this, e.getMessage());
                    }

                    @Override
                    public void onSuccess(String s) {
                        mMProgressDialog.dismiss();
                        MyLog.d(TAG,"login msg = " +s);
                        String exp = JsonUtil.getJsonValuesString(s, "exp");
                        String flag = JsonUtil.getJsonValuesString(s, "flag");
                        if (flag.equals("true")) {
                            timer.start();
                        } else {
                            PhoneUtils.ShowToastMessage(ForgetPasswordActivity.this, exp);
                        }
                    }
                });

    }

    //   倒计时响应事件  timer.start();
    private CountDownTimer timer = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            try {
                btnGetSmsCode.setClickable(false);// 设置不能点击
                btnGetSmsCode.setText(millisUntilFinished / 1000 + getString(R.string.send_again));// 设置倒计时时间
                btnGetSmsCode.setTextColor(getResources().getColor(R.color.appTipColor)); // 设置为灰色，这时是不能点击的
            } catch (Exception e) {
                MyLog.i(TAG, e.toString());
            }

        }

        @Override
        public void onFinish() {
            btnGetSmsCode.setText(getResources().getString(R.string.get_sms_code));
            btnGetSmsCode.setClickable(true);// 重新获得点击
            btnGetSmsCode.setTextColor(getResources().getColor(R.color.appThemeColor));
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }

}
